(ns mttm.models.db.db
  (:use [korma.db]
        [mttm.config.dbconfig]
        [korma.core]))

(defdb prod connection)


(defentity companies)
(defentity roles)
(defentity userroles)
(defentity users)

(defn register-user[user] (insert users (values user)))

(defn register-company[company] (insert companies (values company)))

(defn get-user[username password]
  (first
    (select users
      (where (and (= :username username) (= :password password))))))

(defn append-company-to-user[user](assoc user :company (first (select companies (where (= :id (user :company)))))))


(defn append-roles-to-user[user](assoc user :roles
                                  (select roles (where {:id [in (subselect userroles (fields [:roleid]) (where (= :userid (user :id))))]}))))

;(defn append-roles-to-user[user](assoc user (select roles where (in (:id :roles (map #(% :roleid)(select userroles (fields :roleid) (where (= :userid (user :id))))))))))

(println (append-roles-to-user (append-company-to-user (get-user "username1" "123"))))